<template>
  <view class="addressModify">
    <auto-parse-address
      boxClass="addressModify-autoParseAddress"
      @result="autoParseAddressResult"
    />
    <u--form
      labelPosition="left"
      :model="form"
      :rules="rules"
      ref="addressModifyForm"
      labelWidth="160rpx"
      errorType="toast"
      :labelStyle="{ color: '#909399' }"
    >
      <u-form-item label="姓名" prop="name" borderBottom>
        <u--input
          v-model="form.name"
          border="none"
          placeholder="请输入您的收货人姓名"
        />
      </u-form-item>
      <u-form-item label="手机号" prop="phone" borderBottom>
        <u--input
          v-model="form.phone"
          border="none"
          type="number"
          placeholder="请输入您的收货人手机号"
        />
      </u-form-item>
      <u-form-item label="邮政编码" borderBottom>
        <u--input
          v-model="form.areaCode"
          border="none"
          type="number"
          placeholder="请输入地区邮政编码"
        />
      </u-form-item>
      <u-form-item
        label="地区"
        prop="address"
        borderBottom
        @click="openSelectAddress"
      >
        <u--input
          v-model="form.address"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择省市区"
          border="none"
        />
        <u-icon slot="right" name="arrow-right" color="#606266" />
      </u-form-item>
      <u-form-item label="详细地址" prop="addressDetail" borderBottom>
        <u--textarea
          v-model="form.addressDetail"
          placeholder="请输入详细街道地址"
          autoHeight
          border="none"
        />
      </u-form-item>
    </u--form>
    <view class="addressModify-menu">
      <u-button text="保存" @click="saveForm" />
    </view>

    <u-picker
      :show="addressPicker.visible"
      ref="uPicker"
      :columns="addressPicker.columns"
      keyName="value"
      :defaultIndex="addressPicker.defaultAddressIndex"
      closeOnClickOverlay
      @confirm="addressPickerConfirm"
      @change="changeAddressHandler"
      @close="addressPickerClose"
      @cancel="addressPickerClose"
    />
  </view>
</template>

<script>
import addressOptions from "@/static/address/country-data.js";
export default {
  name: "AddressModify", // 新增 || 修改
  options: { styleIsolation: "shared" }, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
  data() {
    return {
      addressId: "", // 地址Id
      addressPicker: {
        // 地区选择器
        visible: false,
        defaultAddressIndex: [], // 默认值索引
        columns: [], // 数据
      },
      form: {
        // 表单主数据
        name: "",
        phone: "",
        areaCode: "", // 邮政编码
        province: "", // 省份
        city: "", // 城市
        county: "", // 区县
        addressDetail: "", // 详细地址
        address: "", // 省市区组合
      },
      rules: {
        name: {
          type: "string",
          required: true,
          message: "请输入您的收货人姓名",
          trigger: ["blur", "change"],
        },
        phone: {
          type: "string",
          required: true,
          message: "请输入您的收货人手机号",
          trigger: ["blur", "change"],
        },
        address: {
          type: "string",
          required: true,
          message: "请选择省市区",
          trigger: ["blur", "change"],
        },
        addressDetail: {
          type: "string",
          required: true,
          message: "请输入详细街道地址",
          trigger: ["blur", "change"],
        },
      },
    };
  },
  onShow() {
    const routes = getCurrentPages();
    this.addressId = routes[routes.length - 1]?.options?.addressId;

    this.addressId && this.getDetails(); // 获取地址详情

    this.initAddress(); // 初始化地址数据
  },
  methods: {
    // 保存表单
    saveForm() {
      this.$refs.addressModifyForm.validate().then(res => {
				// uni.$u.toast('校验通过')
        this.addressAdd()
			})
    },
    // 新增或修改地址
    async addressAdd() {
      const { code, msg } = await this.$address.addressAdd(this.form)
      if (code === 0) {
        this.showSuccess(msg)
        getCurrentPages().length > 1 && uni.navigateBack() // 成功后返回上一页
      }
    },
    // 自动识别地址回调
    autoParseAddressResult({ province, city, area, detail, name, phone }) {
      this.form.province = province
      this.form.city = city
      this.form.county = area
      this.form.addressDetail = detail
      this.form.name = name
      this.form.phone = phone

      this.form.address = `${province}${city}${area}` // 省市区组合
      this.setDefaultAddressIndex() // 刷新默认值索引 并且赋值数据
    },
    // 选择器关闭回调
    addressPickerClose() {
      this.addressPicker.visible = false;
    },
    // 选择器点击确定按钮，返回当前选择的值
    addressPickerConfirm({ value }) {
      this.form.province = value[0].label
      this.form.city = value[1].label
      this.form.county = value[2].label
      this.form.address = `${value[0].label}${value[1].label}${value[2].label}`;
      this.addressPickerClose();
    },
    // 选择器选择值变化时触发
    changeAddressHandler(e) {
      const {
        columnIndex, // 第几列索引
        index, // 当前列数据索引
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.uPicker,
      } = e;
      // console.log(columnIndex, index, picker)
      if (columnIndex === 0) {
        // 选择第一列
        // 本地数据
        this.addressPicker.columns[1] = addressOptions[index].children; // 地址第二列
        this.addressPicker.columns[2] = addressOptions[index].children[0].children; // 地址第三列
        // 组件数据
        picker.setColumnValues(1, addressOptions[index].children);
        picker.setColumnValues(2, addressOptions[index].children[0].children);
      } else if (columnIndex === 1) {
        // 选择第二列
        this.addressPicker.columns[2] = this.addressPicker.columns[1][index].children;
        picker.setColumnValues(2, this.addressPicker.columns[1][index].children); // 组件数据
      }
    },
    // 打开地址选择器
    openSelectAddress() {
      this.addressPicker.visible = true;
    },
    // 初始化获取地址详情
    async getDetails() {
      const { code, data } = await this.$address.addressGetDetails({
        id: this.addressId,
      });
      if (code === 0) {
        data["address"] = `${data.province}${data.city}${data.county}`;
        this.form = data;
        this.setDefaultAddressIndex()
      }
    },
    // 查找已有数据选择器索引
    setDefaultAddressIndex() {
      const provinceIndex = addressOptions.findIndex(item => item.value.includes(this.form.province)) // 省份索引
      const cityIndex = addressOptions[provinceIndex].children.findIndex(item => item.value.includes(this.form.city)) // 城市索引
      const countyIndex = addressOptions[provinceIndex].children[cityIndex].children.findIndex(item => item.value.includes(this.form.county)) // 区域索引
      // 默认索引设置赋值数据
      this.initAddress(provinceIndex, cityIndex, countyIndex)
    },
    // 设置本地地址data数据和ref组件数据
    initAddress(provinceIndex = 0, cityIndex = 0, countyIndex = 0) {
      // data数据
      this.addressPicker.columns[0] = addressOptions; // 地址第一列
      this.addressPicker.columns[1] = addressOptions[provinceIndex].children; // 地址第二列
      this.addressPicker.columns[2] = addressOptions[provinceIndex].children[cityIndex].children; // 地址第三列
      // ref组件数据
      this.$nextTick(() => {
        this.$refs.uPicker.setColumnValues(0, addressOptions)
        this.$refs.uPicker.setColumnValues(1, addressOptions[provinceIndex].children)
        this.$refs.uPicker.setColumnValues(2, addressOptions[provinceIndex].children[cityIndex].children)

        // 在这里设置默认地址选择索引
        this.addressPicker.defaultAddressIndex = [provinceIndex, cityIndex, countyIndex]
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.addressModify {
  /deep/ &-autoParseAddress {
    width: 100%;
    .auto-textarea {
      background: #fff;
      border-radius: 20rpx
    }
    .auto-btn {
      background: #fff;
      font-size: 24rpx;
      color: #909399;
      border-width: 0.5px !important;
      border-color: $u-border-color !important;
      border-style: solid;
      border-radius: 10rpx
    }
  }
  /deep/ .u-form {
    padding: 30rpx;
    &-item {
      background: #fff;
      &__body {
        padding: 20rpx 10rpx;
        &__left__content__label {
          font-size: 26rpx;
        }
      }
    }
    .u-input__content__field-wrapper__field {
      color: #606266 !important;
      font-size: 26rpx !important;
    }
    .u-textarea {
      padding: 0 !important;
      &__field {
        color: #606266 !important;
        font-size: 26rpx !important;
      }
    }
  }
  /deep/ .u-form-item:first-child{
    border-top-left-radius: 10rpx;
    border-top-right-radius: 10rpx;
  }
  /deep/ .u-form-item:last-child{
    border-bottom-left-radius: 10rpx;
    border-bottom-right-radius: 10rpx;
  }
  &-menu{
    padding: 0 30rpx;
    /deep/ .u-button{
      background-color: $uni-color-primary !important;
      color: #fff;
      border-radius: 20rpx
    }
  }
}
</style>
